package repository

import (
	"errors"

	"away.wei/minidevpos/db"
	"away.wei/minidevpos/global"
	"away.wei/minidevpos/model"
	"gorm.io/gorm"
)

type ProjectTaskRep struct{}

func (s *ProjectTaskRep) Create(projectId int) (int, error) {
	var (
		projectTaskLast db.ProjectTask
		projectTask     db.ProjectTask
		num             int
	)
	if errors.Is(global.DB.Where("project_id=?", projectId).Last(&projectTaskLast).Error, gorm.ErrRecordNotFound) {
		num = 1
	} else {
		num = projectTaskLast.Num + 1
	}
	projectTask.ProjectId = projectId
	projectTask.Num = num
	return num, global.DB.Create(&projectTask).Error
}

func (s *ProjectTaskRep) Delete(ids []int) error {
	return global.DB.Delete(&db.ProjectTask{}, "id in ?", ids).Error
}

func (s *ProjectTaskRep) DeleteByProjectId(projectId int) error {
	return global.DB.Where("project_id=?", projectId).Delete(&db.ProjectTask{}).Error
}

func (s *ProjectTaskRep) GetId(id int) (dto db.ProjectTask, err error) {
	err = global.DB.First(&dto, id).Error
	return dto, err
}

func (s *ProjectTaskRep) GetPage(dto model.ProjectTaskSearch) (list []db.ProjectTask, total int64, err error) {
	limit := dto.PageSize
	offset := dto.PageSize * (dto.Page - 1)

	dbquery := global.DB.Model(&db.ProjectTask{})
	var dtos []db.ProjectTask

	dbquery = dbquery.Where("project_id=?", dto.ProjectId)
	err = dbquery.Count(&total).Error
	if err != nil {
		return
	}
	err = dbquery.Limit(limit).Offset(offset).Order("num desc").Find(&dtos).Error
	return dtos, total, err
}

func (s *ProjectTaskRep) GetGroupAll() (list []db.ProjectTask, err error) {
	dbquery := global.DB.Model(&db.ProjectTask{})
	var dtos []db.ProjectTask
	err = dbquery.Group("project_id").Where("status=0").Find(&dtos).Error
	return dtos, err
}

// status -2终止 -1失败  0待执行 1执行中 2完成
func (s *ProjectTaskRep) UpdateStatus(id, status int) error {
	return global.DB.Model(&db.ProjectTask{}).Where("id=?", id).Update("status", status).Error
}
